package com.party.web.web.controller.subject;

import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.article.Article;
import com.party.core.model.article.ArticleGroup;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.subject.Subject;
import com.party.core.model.subject.SubjectApply;
import com.party.core.model.user.User;
import com.party.core.service.article.IArticleGroupService;
import com.party.core.service.article.IArticleService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.subject.ISubjectApplyService;
import com.party.core.service.subject.ISubjectService;
import com.party.core.service.user.IUserService;
import com.party.web.biz.article.ArticleBizService;
import com.party.web.biz.file.FileBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.output.subject.SubjectOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 专题
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/subject/subject")
public class SubjectController {
	
	@Value("#{party['mic.url']}")
	private String micUrl;

	@Autowired
	private ISubjectService subjectService;

	@Autowired
	private ISubjectApplyService subjectApplyService;

	@Autowired
	private IUserService userService;

	@Autowired
	private FileBizService fileBizService;

	@Autowired
	private IArticleService articleService;

	@Autowired
	private IArticleGroupService articleGroupService;

	@Autowired
	private CosBizService cosBizService;

	@Autowired
	private ArticleBizService articleBizService;

	@Autowired
	private IMemberGroupService memberGroupService;
	
	protected static Logger logger = LoggerFactory.getLogger(SubjectController.class);

	/**
	 * 跳转至列表 我发布的专题
	 * 
	 * @return
	 */
	@RequestMapping(value = "subjectList")
	public ModelAndView subjectList(Subject subject, Page page, CommonInput commonInput) {
		ModelAndView mv = new ModelAndView("subject/subjectList");
		MemberGroup user = RealmUtils.getCurrentUser();
		if(RealmUtils.getNewCurrentUser().isXzgsAdmin()){
			user = memberGroupService.get(user.getPartnerId());
		}
		subject.setDelFlag(BaseModel.DEL_FLAG_NORMAL);

		Map<String, Object> params = CommonInput.appendParams(commonInput);
		List<String> orgIds = memberGroupService.getChildWithMy(user.getId());
		params.put("orgIds", orgIds);

		mv.addObject("input", commonInput);
		List<Subject> subjects = subjectService.webListPage(subject, params, page);

		List<SubjectOutput> subjectOutputs = LangUtils.transform(subjects, input -> {
			String filePath = fileBizService.getUploadCIPath(input.getMemberId(), "subject");
			Map<String, String> qrCodeMap = new HashMap<String, String>();
			SubjectOutput subjectOutput = SubjectOutput.transform(input);
			List<SubjectApply> applies = subjectApplyService.getBySubjectId(input.getId());
			subjectOutput.setSubjectApplies(applies);

			String content = "subject/subject_detail.html?id=" + input.getId();
			String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + input.getId());
			qrCodeMap.put("qrCode", qrCodeUrl);
			qrCodeMap.put("qrCodeContent", micUrl + content);
			subjectOutput.setQrCodeMap(qrCodeMap);

			return subjectOutput;
		});
		mv.addObject("subjects", subjectOutputs);
		mv.addObject("page", page);
		return mv;
	}

	/**
	 * 跳转至发布
	 * 
	 * @param id
	 * @return
	 */
	@DataControl
	@RequestMapping(value = "publishSubject")
	public ModelAndView publishChannel(@ControlParam(table = "subject", column = "member_id", isRequired = false)String id) {
		ModelAndView mv = new ModelAndView("subject/publishSubject");
		if (StringUtils.isNotEmpty(id)) {
			Subject subject = subjectService.get(id);
			mv.addObject("subject", subject);
		}
		return mv;
	}

	/**
	 * 跳转至详情
	 * 
	 * @param id
	 * @return
	 */
	@DataControl
	@RequestMapping(value = "subjectDetail")
	public ModelAndView subjectDetail(@ControlParam(table = "subject", column = "member_id")String id) {
		ModelAndView mv = new ModelAndView("subject/subjectDetail");
		Subject subject = subjectService.get(id);
		mv.addObject("subject", subject);
		return mv;
	}

	/**
	 * 发布保存
	 * 
	 * @param subject
	 * @param result
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "save")
	public AjaxResult save(Subject subject, BindingResult result) {
		String memberId = RealmUtils.getCurrentUser().getId();
		if(RealmUtils.getNewCurrentUser().isXzgsAdmin()){
			memberId = RealmUtils.getNewCurrentUser().getPartnerId();
		}
		AjaxResult ajaxResult = new AjaxResult();
		// 数据验证
		if (result.hasErrors()) {
			List<ObjectError> allErros = result.getAllErrors();
			ajaxResult.setDescription(allErros.get(0).getDefaultMessage());
			return ajaxResult;
		}

		if (StringUtils.isNotEmpty(subject.getId())) {
			Subject db = subjectService.get(subject.getId());
			memberId = db.getMemberId();
			subjectService.update(subject);
		} else {
			User user = userService.findByLoginName("admin");
			subject.setCreateBy(user.getId());
			subject.setUpdateBy(user.getId());
			subject.setMemberId(memberId);
			subjectService.insert(subject);
		}
		ajaxResult.setSuccess(true);

		try {
			String filePath = fileBizService.getUploadCIPath(memberId, "subject");
			String content = "subject/subject_detail.html?id=" + subject.getId();
			fileBizService.uploadCloudOut(subject.getId(), filePath, content, memberId);
		} catch (Exception e) {
			logger.error("生成专题二维码异常", e);
		}
		return ajaxResult;
	}
	
	/**
	 * 删除专题
	 */
	@DataControl
	@ResponseBody
	@RequestMapping(value = "delete")
	public AjaxResult delete(@ControlParam(table = "subject", column = "member_id")String id) {
		AjaxResult ajaxResult = new AjaxResult();
		try {
			if (StringUtils.isEmpty(id)) {
				return new AjaxResult(false);
			}

			List<SubjectApply> applies = subjectApplyService.getBySubjectId(id);
			if (applies.size() > 0) {
				return new AjaxResult(false, "该专题下已有栏目");
			}

			subjectService.delete(id);
			ajaxResult.setSuccess(true);
			return ajaxResult;
		} catch (Exception e) {
			logger.error("专题删除异常", e);
		}
		ajaxResult.setSuccess(false);
		return ajaxResult;
	}

	/**
	 * 复制主题
	 * @param subjectId 主题ID
	 * @return
	 */
	@DataControl
	@ResponseBody
	@Transactional
	@RequestMapping(value = "copySubject")
	public AjaxResult copySubject(@ControlParam(table = "subject", column = "member_id")String subjectId){
		AjaxResult ajaxResult = new AjaxResult();
		//获取主题信息
		if(StringUtils.isBlank(subjectId)){
			ajaxResult.setSuccess(false);
			ajaxResult.setDescription("输入了无效数据");
			return ajaxResult;
		}
		//复制指定主题
		Subject subject = subjectService.get(subjectId);

		String memberId = subject.getMemberId();

		clearData(subject);
		subject.setMemberId(memberId);
		String id = subjectService.insert(subject);

		try {
			String filePath = fileBizService.getUploadCIPath(memberId, "subject");
			String content = "subject/subject_detail.html?id=" + subject.getId();
			fileBizService.uploadCloudOut(subject.getId(), filePath, content, memberId);
		} catch (Exception e) {
			logger.error("生成专题二维码异常", e);
		}

		//复制获取到的栏目信息
		SubjectApply subjectApply = new SubjectApply();
		subjectApply.setSubjectId(subjectId);
		subjectApply.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
		List<SubjectApply> applies = subjectApplyService.list(subjectApply);
		for(SubjectApply apply : applies){
			//复制获取到的每一个栏目下的具体信息
			if(apply.getType().equals("article")){
				//单篇文章
				Article article = articleService.get(apply.getTargetId());
				if(article != null){
					clearData(article);
					article.setReadNum(0);
					article.setMemberId(memberId);
					String articleId = articleService.insert(article);

					try {
						articleBizService.uploadQrCode(article.getMemberId(), article.getId());
					} catch (Exception e) {
						logger.error("生成文章二维码异常", e);
					}

					String url = apply.getUrl();
					if (StringUtils.isNotEmpty(url)) {
						String newUrl = url.substring(0, url.lastIndexOf("=") + 1) + articleId;
						apply.setUrl(newUrl);
					}
					apply.setTargetId(articleId);
				}
			}else if(apply.getType().equals("channel")){
				//文章列表（文章组 articleGroup）
				ArticleGroup articleGroup = articleGroupService.get(apply.getTargetId());
				articleGroup.setMemberId(memberId);
				clearData(articleGroup);
				String articleGroupId = articleGroupService.insert(articleGroup);

				Article article = new Article();
				article.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
				article.setArticleGroupId(apply.getTargetId());
				List<Article> articles = articleService.listPage(article,null);
				for(Article a : articles){
					clearData(a);
					a.setArticleGroupId(articleGroupId);
					a.setReadNum(0);
					a.setMemberId(memberId);
					articleService.insert(a);

					try {
						articleBizService.uploadQrCode(a.getMemberId(), a.getId());
					} catch (Exception e) {
						logger.error("生成文章二维码异常", e);
					}
				}
				String url = apply.getUrl();
				if (StringUtils.isNotEmpty(url)) {
					String newUrl = url.substring(0, url.lastIndexOf("=") + 1) + articleGroupId;
					apply.setUrl(newUrl);
				}
				apply.setTargetId(articleGroupId);
			} else if (apply.getType().equals(SubjectApply.TYPE_URL)) {
				apply.setTargetId(null);
			}

			clearData(apply);
			apply.setSubjectId(id);
			apply.setMemberId(memberId);
			subjectApplyService.insert(apply);
		}
		ajaxResult.setSuccess(true);
		return ajaxResult;
	}

	/**
	 * 清除数据
	 * @param obj 被清除的对象
	 */
	private void clearData(BaseModel obj){
		if(obj == null){
			return;
		}
		obj.setId(null);
		obj.setCreateDate(null);
		obj.setUpdateDate(null);
	}
}
